/**
 * 应用全局配置
 * 提供全局数据和方法
 */

App({
  /**
   * 全局数据
   */
  globalData: {
    userInfo: null,
    processedCount: 0,
    history: [],
    selectedImages: null,
    settings: {
      defaultQuality: 80,
      defaultFormat: 'jpg',
      autoSave: true,
      showTips: true
    }
  },

  /**
   * 应用启动时执行
   */
  onLaunch() {
    console.log('图像处理大师启动');
    this.initSystemInfo();
    this.loadUserSettings();
    this.loadHistory();
  },

  /**
   * 初始化系统信息
   */
  initSystemInfo() {
    try {
      const systemInfo = wx.getSystemInfoSync();
      this.globalData.systemInfo = systemInfo;
      
      // 根据设备性能调整默认设置
      if (systemInfo.platform === 'android' && systemInfo.benchmarkLevel < 1000) {
        this.globalData.settings.defaultQuality = 70;
      }
      
    } catch (error) {
      console.error('获取系统信息失败:', error);
    }
  },

  /**
   * 加载用户设置
   */
  loadUserSettings() {
    try {
      const settings = wx.getStorageSync('userSettings');
      if (settings) {
        this.globalData.settings = { ...this.globalData.settings, ...settings };
      }
    } catch (error) {
      console.error('加载用户设置失败:', error);
    }
  },

  /**
   * 保存用户设置
   */
  saveUserSettings() {
    try {
      wx.setStorageSync('userSettings', this.globalData.settings);
    } catch (error) {
      console.error('保存用户设置失败:', error);
    }
  },

  /**
   * 加载历史记录
   */
  loadHistory() {
    try {
      const history = wx.getStorageSync('processingHistory');
      if (history) {
        this.globalData.history = history;
        this.globalData.processedCount = history.length;
      }
    } catch (error) {
      console.error('加载历史记录失败:', error);
    }
  },

  /**
   * 添加到历史记录
   */
  addToHistory(item) {
    try {
      // 限制历史记录数量
      const maxHistory = 50;
      this.globalData.history.unshift(item);
      
      if (this.globalData.history.length > maxHistory) {
        this.globalData.history = this.globalData.history.slice(0, maxHistory);
      }
      
      this.globalData.processedCount = this.globalData.history.length;
      
      // 保存到本地存储
      wx.setStorageSync('processingHistory', this.globalData.history);
      
    } catch (error) {
      console.error('保存历史记录失败:', error);
    }
  },

  /**
   * 清空历史记录
   */
  clearHistory() {
    this.globalData.history = [];
    this.globalData.processedCount = 0;
    
    try {
      wx.removeStorageSync('processingHistory');
    } catch (error) {
      console.error('清空历史记录失败:', error);
    }
  },

  /**
   * 获取用户授权状态
   */
  async checkAuth(scope) {
    return new Promise((resolve) => {
      wx.getSetting({
        success: (res) => {
          resolve(!!res.authSetting[scope]);
        },
        fail: () => {
          resolve(false);
        }
      });
    });
  },

  /**
   * 请求用户授权
   */
  async requestAuth(scope) {
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope,
        success: resolve,
        fail: reject
      });
    });
  },

  /**
   * 显示权限提示
   */
  showAuthModal(title, content) {
    return new Promise((resolve) => {
      wx.showModal({
        title,
        content,
        showCancel: false,
        success: () => {
          wx.openSetting();
          resolve();
        }
      });
    });
  },

  /**
   * 全局错误处理
   */
  onError(error) {
    console.error('应用错误:', error);
    
    // 记录错误日志
    this.logError(error);
  },

  /**
   * 记录错误日志
   */
  logError(error) {
    try {
      const errorLog = {
        message: error.message,
        stack: error.stack,
        timestamp: new Date().toISOString(),
        systemInfo: this.globalData.systemInfo
      };
      
      // 这里可以发送到错误收集服务
      console.error('错误日志:', errorLog);
      
    } catch (e) {
      console.error('记录错误失败:', e);
    }
  },

  /**
   * 获取网络状态
   */
  async getNetworkType() {
    return new Promise((resolve) => {
      wx.getNetworkType({
        success: (res) => {
          resolve(res.networkType);
        },
        fail: () => {
          resolve('unknown');
        }
      });
    });
  },

  /**
   * 显示网络提示
   */
  async showNetworkTip() {
    const networkType = await this.getNetworkType();
    
    if (networkType === 'none') {
      wx.showToast({
        title: '网络不可用',
        icon: 'none'
      });
      return false;
    }
    
    if (networkType === '2g' || networkType === '3g') {
      wx.showToast({
        title: '网络较慢，可能影响体验',
        icon: 'none'
      });
    }
    
    return true;
  }
});